package cfengMiddleware.server.rabbitmq.consumer;

import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/22
 *  redisson基于主题方式的发布订阅没有自动监听的功能，只能通过轮询的方式
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class RedissonTopicConsumer implements ApplicationRunner, Ordered {

    private final RedissonClient redissonClient;

    //run方法会在容器启动后执行其中的代码，需要在方法里实现不断监听主题中的消息的动态，间接实现自动监听消费
    @Override
    public void run(ApplicationArguments args) throws Exception {
        final String key = "redissonMsgTopicKey";
        try {
            RTopic rTopic = redissonClient.getTopic(key);
            rTopic.addListener(MessageEntity.class, (charSequence, messageEntity) -> {
                log.info("redisson消费者监听到消息： {}",messageEntity);
                if(!Objects.isNull(messageEntity)) {
                    //执行业务逻辑
                    log.info("处理用户： {}",messageEntity.getId());
                }
            });
        } catch (Exception e) {
            log.error("消费者发生异常：{}",e);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
